package com.cdshangpai;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;

import com.cdshangpai.photoapp.LogConfig;
import com.cdshangpai.photoapp.ui.LoveActivity;
import com.cdshangpai.photoapp.ui.caseui.CaseDetailActivity;
import com.cdshangpai.photoapp.ui.hotal.HotalDetailActivity;
import com.cdshangpai.photoapp.ui.main.LoginFragment;
import com.cdshangpai.utils.offlinecache.CacheManager;
import com.cdshangpai.utils.offlinecache.NetworkState;

public class PhotoappApplication extends Application {
    public static Context context;
    private NetworkState networkState = new NetworkState();
    private CacheManager cacheManager;

    @Override
    public void onCreate() {
        super.onCreate();

        init();

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
        context = getApplicationContext();

        networkState.registNetworkStateListener();

        //app启动同时启动缓存处理器
        cacheManager = new CacheManager();
        cacheManager.beginTask();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        networkState.unregistNetworkStateListener();
    }

    private int count=0;
    private void init() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            }

            @Override
            public void onActivityStarted(Activity activity) {
                count++;
            }

            @Override
            public void onActivityResumed(Activity activity) {
            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
                count--;
                if(count==0)
                {
                    Log.i(LogConfig.logTag,"退出到后台");
//                    logout();
                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
            }
        });
    }

    private void logout()
    {
        CaseDetailActivity.clearSelected();
        HotalDetailActivity.cleanSelected();
        LoginFragment.logout();
        LoveActivity.cleanContent();
    }
}
